<?php
	if (!isset($_SESSION)) {
		 session_start();
	}
	
	// Clear previous messages.
	if(isset($_SESSION['error'])) session_unregister('error');
	if(isset($_SESSION['success'])) session_unregister('success');

	// Get values from the page.
	$username = addslashes($_POST['userName']);
	$password = MD5(addslashes($_POST['userPassword'])); 
	
	// Setting the default page to return.
	$_SESSION['page'] = "index.php";
	
	// Validate values from the page.
	if($username == "" || $password == ""){
		$_SESSION['error'] = "Both user name and password are mandatory.";
	}else{
		// Check for the user.
		include("../dbconnection.php");
		if($result = mysql_query("SELECT * FROM users WHERE userName='$username'")){
			if(mysql_num_rows($result) == 1){
				$row = mysql_fetch_assoc($result);
				$loginAttempts = $row['loginAttempts'] + 1;
				$today = date('Y-m-d');
				if($row['status'] == 'INACTIVE'){	// Check whether the user is INACTIVE.
					if($row['userTypeId'] == 2)
						$_SESSION['error'] = "Please contact us to reset password (example@abc.com).";
					else
						$_SESSION['error'] = "Please contact owner to active your account.";
					mysql_query("UPDATE users SET lastLogDate = '$today' WHERE userName = '$username'");
				}else if($loginAttempts > 3){		// Check whether the user has tried for more than 3 times to log.
					if($row['userTypeId'] == 2)
						$_SESSION['error'] = "Please contact us to reset password (example@abc.com).";
					else
						$_SESSION['error'] = "Please contact owner to active your account.";
					mysql_query("UPDATE users SET status = 'INACTIVE', lastLogDate = '$today' WHERE userName = '$username'");
				}else if($password != $row['userPassword']){	// Check for password match.
					$_SESSION['error'] = "Please enter the password correctly.";
					mysql_query("UPDATE users SET loginAttempts = '$loginAttempts', lastLogDate = '$today' WHERE userName = '$username'");
				}else{		// User is OK to log into the system.
					mysql_query("UPDATE users SET loginAttempts = '0', lastLogDate = '$today' WHERE userName = '$username'");
					$_SESSION['userName'] = $username;
					$_SESSION['userPassword'] = $password;
					$_SESSION['userTypeId'] = $row['userTypeId'];
					$_SESSION['page'] = "home.php";
				}
			}else{
				$_SESSION['error'] = "Incorrect UserName or Password.";
			}
		}else{
			$_SESSION['error'] = "Error occured!";
		}
	}
	header('Location: ../../');	
?>
